/*
 * Galaxium Messenger
 * Copyright (C) 2007 Ben Motmans <ben.motmans@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.Text;
using System.Collections.Generic;

using Anculus.Core;
using Galaxium.Core;

namespace Galaxium.Protocol
{
	public class TextMessage : ITextMessage
	{
		protected IEntity _source;
		protected DateTime _timestamp;
		protected List<IEmoticon> _customEmoticons;
		protected List<ITextChunk> _chunks;
		
		public TextMessage (IEntity source, string message)
			: this (source, DateTime.Now, message)
		{
		}

		public TextMessage (IEntity source, DateTime timestamp, string message)
			: this (source, timestamp, (IEnumerable<ITextChunk>)null)
		{
			ThrowUtility.ThrowIfNull ("message", message);
			
			_chunks.Add (new TextChunk(new TextStyle(), TextChunkType.Text, message));
			
			Split();
		}
		
		public TextMessage (IEntity source, IEnumerable<ITextChunk> chunks)
			: this (source, DateTime.Now, chunks)
		{
		}
		
		public TextMessage (IEntity source, DateTime timestamp, IEnumerable<ITextChunk> chunks)
		{
			_source = source;
			_timestamp = timestamp;
			_customEmoticons = new List<IEmoticon>();
			_chunks = new List<ITextChunk>();
			
			if (chunks != null)
				_chunks.AddRange (chunks);
		}

		public List<IEmoticon> CustomEmoticons
		{
			get { return _customEmoticons; }
			set { _customEmoticons = value; Split(); }
		}

		public IEntity Source
		{
			get { return _source; }
			protected set { _source = value; }
		}
		
		public DateTime TimeStamp
		{
			get { return _timestamp; }
		}

		public IEnumerable<ITextChunk> Chunks
		{
			get { return _chunks; }
		}

		public string GetText ()
		{
			StringBuilder sb = new StringBuilder ();
			foreach (ITextChunk chunk in _chunks)
				sb.Append (chunk.Text);
			return sb.ToString ();
		}
		
		public virtual void SetText (string txt)
		{
			_chunks.Clear ();
			_chunks.Add (new TextChunk (new TextStyle (), TextChunkType.Text, txt));
			Split ();
		}
		
		public virtual void Split()
		{
			//_chunks = new List<ITextChunk>();
		}
		
		protected void SetChunks(List<ITextChunk> newChunks)
		{
			_chunks = newChunks;
		}
	}
}